var id;

// 选择ztree
var setting = {
  check: {
    enable: true
  },
  data: {
    simpleData: {
      enable: false
    }
  },
  view: {
    showIcon: false
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

/**标准数据格式*/
var zNodes = [];

// 选中的zTree值
var participantId = [];

$(function() {
  $(".validform").createForm();
  id = ly.getUrlParam("id") || '';
  if (id) {
    $(".body_title").html("编辑");
    $(".form").getForm({
      id: id,
      ajaxform: true,
    }, function(data) {
      if(data.usersList&&data.usersList.length){
        var currStr='';
        for (var i = 0; i <data.usersList.length; i++) {
          var usersInfo = data.usersList[i];
            if(i==data.usersList.length-1){
              currStr +=usersInfo.nickName+"&nbsp;&nbsp;&nbsp;&nbsp;";
            }else{
              currStr +=usersInfo.nickName+'、'
            }
        }
        $(".addboxlist").html(currStr);
      }
			getTeamUser(data.usersList); // 获取部门与人员集合

    });
  } else {
		getTeamUser(); // 获取部门与人员集合

  }

  //提交
  $("body").on("click", "#save-btn", function(event) {
    event.preventDefault();
    var success = $('.form').validate('submitValidate');
    var title = $("#title").val(); // 消息标题
    var content = $("#content").val(); // 消息内容
		
		// 获取选中人员Id集合
		var participantIdArr = participantId.toString();
		
		if (participantIdArr == '') {
			ly.toast('请选择接收人');
      return;
		}

    if (success) {
      var obj = {};
      var url = site.apiUrl + "/back/announcement/insertOrUpdateAnnouncement";
      if (id) {
        //修改
        obj = {
          'title': title,
          'content': content,
					'id': id,
					'userId': participantIdArr,
        };
      } else {
        //新增
        obj = {
          'title': title,
          'content': content,
					'userId': participantIdArr,
        };
      }
      request({
        url: url,
        data: obj,
        type: "post",
        callback: function(f) {
          if (f.code == "rest.success") {
            if (id == '') {
              ly.alert('保存成功', function() {
                ly.goto("notice-list.html");
              });
            } else {
              ly.alert('修改成功', function() {
                ly.goto("notice-list.html");
              });
            }
          } else {
            ly.toast(f.desc);
          }
        }
      });

    }
  })

	// 点击显示--选择部门人员弹窗
  $("#changePerson").on("click", function() {
    var index = layer.open({
      title: false,
      type: 1,
      area: ['600px'], //设置宽度,高度自适应
      closeBtn: 0,
      content: $(".layerBox"),
      success: function(layero, index) {
        $("#layui-layer" + index).find(".goback,.icon-close").on("click", function() {
					layer.close(index);
        });
        $("#sayerBox-btn").on("click", function() {
					getzTreeChecked();
					ly.toast('选择成功')
					layer.close(index);
        })
      }
    });
  })
});

// zTree发生改变
function zTreeOnCheck(event, treeId, treeNode) {
	var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
	$("#ztreeCheckedNames").html('');
	for(var i = 0; i < checkedNodes.length; i++) {
    if (!checkedNodes[i].children) {
      $("#ztreeCheckedNames").append('<li>'+ checkedNodes[i].name +'</li>')
    }
  }
};

// 获取zTree选中的值
function getzTreeChecked() {
	participantId = [];
  var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
	var checkedNodes = zTreeObj.getCheckedNodes();
  var currStr='';
	$.each(checkedNodes, function(i, o) {
		if (checkedNodes[i].userId) {
			participantId.push(checkedNodes[i].userId);
      if(i==checkedNodes.length-1){
        currStr +=checkedNodes[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;";
      }else{
        currStr +=checkedNodes[i].name+'、';
      }
		}
	}) 
  $(".addboxlist").html(currStr);
}

// 获取部门与人员集合
function getTeamUser(viewData) {
	request({
    url: site.apiUrl + "/back/team/selectTeamUserByGroupsBack",
    type: "get",
    callback: function(f) {
      if (f.code == "rest.success") {
				zNodes = f.result;
				if (!viewData) { // 新增
					$("#ztreeCheckedNames").html('');
					$.fn.zTree.init($("#treeDemo"), setting, zNodes); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
					zTreeObj.expandAll(false); // 收起所有节点
				} else { // 编辑
					var viewCheckedPerson = zNodes.map(function (item) {
						if (item.children && item.children.length > 0) {
							var childrenCheckOption = item.children;
							var newChildren = childrenCheckOption.map(function (itm) {
								// 判断选中项，true设置cheked=true，反之设为false
								var isCheckedOption = viewData.some(function (items) {
									return items.userId === itm.userId;
								});
								if (isCheckedOption) {
									itm.checked = true; // 为true时zTree勾选当前项
								} else {
									itm.checked = false;
								}
								return itm;
							});
							item.children = newChildren;
							return item;
						} else {
              return item;
            }
					});
					$.fn.zTree.init($("#treeDemo"), setting, viewCheckedPerson); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.expandAll(false); // 收起所有节点
          zTreeOnCheck(); // 展示右侧选中项
          
          // 设置编辑默认选中值
          participantId = [];
          $.each(viewData, function(i, o) {
            participantId.push(viewData[i].userId);
          })
				}
      }
    }
  });
}